<template>
  <a-list-item class="comment-item">
    <!-- 单个评论的核心内容 -->
    <a-comment class="comment-card">
      <template #avatar>
        <a-avatar :src="comment.user?.userAvatar" size="small" class="comment-avatar" />
      </template>
      <template #author>
        <span class="comment-author">{{ comment.user?.userName }}</span>
      </template>
      <template #datetime>
        <span class="comment-time">{{ formatTime(comment.createTime) }}</span>
      </template>
      <template #content>
        <p class="comment-content">{{ comment.content }}</p>
      </template>

      <!-- 评论操作区：点赞、回复、删除、展开/收起子评论 -->
      <template #actions>
        <!-- 点赞：根据isLike状态动态切换图标和颜色 -->
        <span
          class="comment-action like-action"
          @click="handleLike(comment)"
          :style="{ color: comment.isLike ?? false ? '#f5222d' : '#666' }"
        >
        <!-- 核心：监听isLike变化，切换图标（LikeFilled=已点赞，LikeOutlined=未点赞） -->
        <template v-if="comment.isLike ?? false">
          <LikeFilled />
        </template>
        <template v-else>
          <LikeOutlined />
        </template>
        {{ comment.likeCount ?? 0 }}
        </span>
        <!-- 回复 -->
        <span class="comment-action reply-action" @click="handleReply(comment)">
          回复
        </span>
        <!-- 删除（权限判断） -->
        <span v-if="canDelete(comment)" class="comment-action delete-action" @click="handleDelete(comment)">
          <DeleteOutlined /> 删除
        </span>
        <!-- 展开/收起子评论（有子评论时显示） -->
        <span v-if="comment.children?.length" class="comment-action toggle-action" @click="comment.expanded = !comment.expanded">
          {{ comment.expanded ? '收起回复' : `查看${comment.children.length}条回复` }}
        </span>
      </template>

      <!-- 子评论区域：递归调用自身渲染子评论（无限层级） -->
      <div
        v-if="comment.expanded && comment.children?.length"
        class="child-comments"
      >
        <a-list :data-source="comment.children" item-layout="horizontal">
          <!-- 递归渲染：用 CommentItem 渲染每一个子评论 -->
          <template #renderItem="{ item }">
            <CommentItem
              :comment="item"
              :login-user="loginUser"
              :reply-target="replyTarget"
              :reply-content="replyContent"
              @handle-like="handleLike"
              @handle-reply="handleReply"
              @handle-delete="handleDelete"
              @cancel-reply="cancelReply"
              @send-reply="handleSendReply"
              @update:replyContent="newValue => emit('update:replyContent', newValue)"
            />
          </template>
        </a-list>
      </div>

      <!-- 回复输入框（针对当前评论） -->
      <div v-if="replyTarget === comment" class="reply-input-container">
        <a-comment class="reply-card">
          <template #avatar>
            <a-avatar :src="loginUser?.userAvatar"  class="reply-avatar" />
          </template>
          <template #content>
            <a-textarea
              ref="replyTextareaRef"
              :value="replyContent"
              :rows="2"
              placeholder="写下你的回复..."
              @change="handleReplyContentChange"
              @pressEnter="handleSendReply"
              class="reply-input"
            />
            <div style="margin-top: 8px">
              <a-button type="primary" @click="handleSendReply" class="reply-btn">发送</a-button>
              <a-button style="margin-left: 8px" @click="cancelReply" class="cancel-btn">取消</a-button>
            </div>
          </template>
        </a-comment>
      </div>
    </a-comment>
  </a-list-item>
</template>

<script setup lang="ts">
import { defineProps, defineEmits, defineOptions, ref } from 'vue'
// 新增：引入已点赞图标 LikeFilled
import { LikeOutlined, LikeFilled, DeleteOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import type { CommentExtendVO } from '@/components/modal/PictureCommentModal.vue'

// 关键：递归组件必须指定组件名，否则模板无法识别自身
defineOptions({
  name: 'CommentItem'
})

// 定义Props：接收当前评论、登录用户、回复状态等
interface Props {
  comment: CommentExtendVO // 当前要渲染的评论（包含children和expanded）
  loginUser?: API.UserVO // 登录用户信息
  replyTarget: CommentExtendVO | null // 当前激活回复的评论
  replyContent: string // 回复内容
}

const props = withDefaults(defineProps<Props>(), {
  replyContent: ''  // 默认为空字符串
})

// 定义事件：将子组件的交互事件传递给父组件（主组件）
const emit = defineEmits<{
  (e: 'handle-like', comment: CommentExtendVO): void
  (e: 'handle-reply', comment: CommentExtendVO): void
  (e: 'handle-delete', comment: CommentExtendVO): void
  (e: 'cancel-reply'): void
  (e: 'send-reply'): void
  (e: 'update:replyContent', value: string): void  // 新增：通知父组件更新回复内容
}>()

// 处理输入变化：通过 emit 通知父组件更新 prop
const handleReplyContentChange = (e: Event) => {
  // 从事件对象中取输入值（Ant Design 的 change 事件传递的是原生 Event）
  const inputValue = (e.target as HTMLTextAreaElement).value || ''
  emit('update:replyContent', inputValue)  // 父组件会监听此事件并更新 replyContent
}

// 获取输入框 DOM 引用
const replyTextareaRef = ref<HTMLTextAreaElement | null>(null)

// 时间格式化（复用原逻辑）
const formatTime = (time: string | Date | undefined) => {
  if (!time) return ''
  if (time instanceof Date) {
    return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
  }
  // 如果是字符串，尝试解析为日期
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 权限判断（复用原逻辑）
const canDelete = (comment: CommentExtendVO) => {
  if (!props.loginUser) return false
  return props.loginUser.id === comment.userId || props.loginUser.userRole === 'admin'
}

// 转发事件：将子组件的交互转发给父组件（复用原逻辑）
const handleLike = (comment: CommentExtendVO) => {
  emit('handle-like', comment)
}

const handleReply = (comment: CommentExtendVO) => {
  emit('handle-reply', comment)
}

const handleDelete = (comment: CommentExtendVO) => {
  emit('handle-delete', comment)
}

const cancelReply = () => {
  emit('cancel-reply')
}

const handleSendReply = () => {
  emit('send-reply')
}
</script>

<style scoped>
/* 评论项整体样式 - 降低高度 */
.comment-item {
  padding: 6px 0 !important; /* 减少上下内边距 */
  line-height: 1.4; /* 减小行高 */

  &:last-child {
    border-bottom: none;
  }
}

.comment-card {
  margin: 0;
  padding: 4px 0; /* 减少卡片内边距 */
  transition: background-color 0.2s;

  &:hover {
    background-color: #fafafa;
  }

  .ant-comment-avatar {
    margin-right: 12px;
  }

  .ant-comment-content {
    flex: 1;
  }

  .ant-comment-actions {
    margin-top: 4px;
    padding-top: 4px;
  }
}

/* 评论元素样式 */
.comment-avatar {
  width: 36px;
  height: 36px;
  border: 1px solid #eee;
}

.comment-author {
  font-weight: 500;
  color: #333;
  font-size: 13px; /* 缩小作者名 */
  margin-right: 6px;
}

.comment-time {
  color: #999;
  font-size: 11px; /* 缩小时间字体 */
}

.comment-content {
  color: #555;
  margin: 2px 0 4px 0 !important; /* 减少内容区域上下间距 */
  font-size: 13px; /* 缩小内容字体 */
  line-height: 1.4;
}

/* 评论操作按钮（移除原like-action固定红色，改为动态绑定） */
.comment-action {
  /* 原有固定颜色移除，改为通过:style动态绑定 */
  font-size: 12px !important; /* 缩小操作按钮字体 */
  margin-right: 12px !important; /* 减少按钮间距 */
  padding: 2px 0;
  cursor: pointer; /* 增加鼠标悬浮指针，提升交互体验 */

  &:hover {
    color: #1890ff;
  }
}

/* 点赞按钮 hover 样式优化（已点赞时hover保持红色） */
.like-action:hover {
  color: #f5222d !important;
}

.reply-action {
  color: #666;
}

.delete-action {
  color: #666;
}

.toggle-action {
  color: #666;
  font-size: 12px;
}

/* 子评论样式 */
.child-comments {
  margin-left: 36px; /* 缩进更大，明确区分层级 */
  margin-top: 4px;
  padding-top: 4px;
  border-left: 2px solid #f0f0f0;
  padding-left: 12px;
}

/* 回复输入框样式 - 与评论主体区分 */
.reply-input-container {
  margin-top: 6px !important;
  margin-left: 42px !important;
}

.reply-card {
  background-color: #f9f9f9;
  padding: 8px !important; /* 减少回复框内边距 */
  border-radius: 8px;
  margin: 0;
}

.reply-avatar {
  width: 32px;
  height: 32px;
}

.reply-input {
  border: 1px solid #e0e0e0;
  min-height: 50px !important; /* 降低回复框高度 */
  font-size: 13px !important;
  border-radius: 4px !important;

  &:focus {
    border-color: #1890ff;
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
  }
}

/* 回复按钮样式 */
.reply-btn {
  background-color: #1890ff !important;
  border-color: #1890ff !important;
  color: white !important;
  transition: all 0.2s !important;
}

.reply-btn:hover {
  background-color: #096dd9 !important;
  border-color: #096dd9 !important;
}


.cancel-btn {
  background-color: #f5f5f5 !important;
  border-color: #d9d9d9 !important;
  color: #666 !important;
  transition: all 0.2s !important;

  &:hover {
    background-color: #e9e9e9 !important;
    border-color: #c0c0c0 !important;
  }
}
</style>
